package com.example.demo.demoApi.apiHandler.cancelClean;

import com.example.demo.demoApi.apiHandler.ApiMsgTypeHandler;

import com.example.demo.demoApi.apiHandler.ResponseHeader;
import com.example.demo.demoApi.msg.AbstractMsg;
import com.example.demo.entity.ExecuteInformationEntity;
import com.example.demo.exception.APICommonCode;
import com.example.demo.exception.BizErrorCode;
import com.example.demo.exception.BizException;
import com.example.demo.taskSchedule.DataProcessSchedule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 取消正在执行或排队的数据库删除或者归档计划
 */
@Slf4j
@Component
public class CancelCleanHandler implements ApiMsgTypeHandler<CancelCleanMsg> {

    @Autowired
    private DataProcessSchedule dataProcessSchedule;

    @Override
    public AbstractMsg handle(CancelCleanMsg msg) {
        CancelCleanResponseMsg responseMsg = new CancelCleanResponseMsg();
        ResponseHeader responseHeader = responseMsg.getHeader();
        responseHeader.setResponseId(msg.getRequestId());
        responseHeader.setMsgType(msg.getMsgType());
        try {
            log.info(msg.getClass().getName() + " handle:", msg);
            CancelCleanRequestBody requestBody = msg.getBody();
            if(requestBody==null || requestBody.getTableName()==null || requestBody.getTableName().length()==0){
                throw new BizException(BizErrorCode.TABLE_NAME_CAN_NOT_BE_NULL);
            }
            ExecuteInformationEntity executeInformation = dataProcessSchedule.cancelDataProcessTask(requestBody.getTableName());
            CancelCleanResponseBody responseBody = new CancelCleanResponseBody();
            responseBody.setExecuteInformation(executeInformation);
            responseMsg.setBody(responseBody);
        }catch (BizException e){
            responseHeader.setCode(e.getErrorCode().getCode()+"");
            responseHeader.setMsg(e.getErrorCode().getMsg());
        }catch (Exception e){
            responseHeader.setCode(APICommonCode.FAIL.getCode());
            responseHeader.setMsg(APICommonCode.FAIL.getCode());
        }
        return responseMsg;
    }

    @Override
    public Class getHandleMsgType() {
        return CancelCleanMsg.class;
    }
}
